#include "MessageBox.h"
#include "hotkeyedit.h"
#include "models/command.h"
#include "models/databasemanager.h"
#include "mainwindow.h"
#include "models/syssettingmodel.h"

#include <QHeaderView>
#include <QLineEdit>
#include <QScroller>
#include <QVBoxLayout>
#include "uppersettingwidget.h"

UpperSettingWidget::UpperSettingWidget(QWidget *parent)
    : QWidget(parent)
{
    initUI();
}

UpperSettingWidget::~UpperSettingWidget()
{
    if(isVisible())
    {
        saveData();
    }
}

void UpperSettingWidget::initUI()
{
    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(int(10*g_xScale));
    // 创建顶部工具栏
    QWidget* toolbar = new QWidget(this);
    toolbar->setFixedHeight(int(60*g_yScale));
    QHBoxLayout* toolbarLayout = new QHBoxLayout(toolbar);
    toolbarLayout->setContentsMargins(28, 0, 28, 0);
    toolbarLayout->setSpacing(int(20*g_xScale));

    // 创建新增按钮
    m_pNewButton = new TouchButton(tr("新建"),toolbar);
    m_pNewButton->setStyleSheet(QString("QPushButton{\
        background:transparent; \
        color:#007BFF;\
        font:%1px \"微软雅黑\"; \
        border-color: #098CFF;\
        border-width:1px;}\
        QPushButton:pressed{ \
        color:#0056b3;}").arg(int(20*g_xScale)));
    toolbarLayout->addStretch();
    toolbarLayout->addWidget(m_pNewButton);
    //表头样式
        QString headerStyle = QString(
              "QHeaderView {"
              "    border: none;"
              "}"
              "QHeaderView::section {"
              "    background-color: #232426;"
              "    color: white;"
              "    font: %1px '微软雅黑';"
              "    border: none;"
              "    border-bottom: 1px solid #48494E;"
              "    border-right: 1px solid #48494E;"
              "    padding-left: 5px;"
              "}"
              "QHeaderView::section:last {"
              "    border-right: none;"
              "}").arg(int(18*g_xScale));
    // 表格的样式
    QString treeStyle = "QTreeView {"
                        "    background-color: #232426;"
                        "    border: 1px solid #48494E;"
                        "    color: white;"
                        "    gridline-color: #48494E;"
                        "}"
                        "QTreeView::item {"
                        "    border-right: 1px solid #48494E;"
                        "    border-bottom: 1px solid #48494E;"
                        "}"
                        "QTreeView::item:last {"
                        "    border-right: none;"
                        "}"
                        "QTreeView::branch:has-children:!has-siblings:closed,QTreeView::branch:closed:has-children:has-siblings{"
                        "border-image: none; image: none;"
                        "}"
                        "QTreeView::branch:open:has-children:!has-siblings,QTreeView::branch:open:has-children:has-siblings{"
                        "border-image: none; image: none;"
                        "}";

    m_pTree = new QTreeWidget(this);
    m_pTree->setColumnCount(5);
    m_pTree->headerItem()->setText(0,"动作");
    m_pTree->headerItem()->setText(1,"HEX");
    m_pTree->headerItem()->setText(2,"文件");
    m_pTree->headerItem()->setText(3,"快捷键");
    m_pTree->headerItem()->setText(4,"操作");
    m_pTree->header()->setSectionResizeMode(0,QHeaderView::Fixed);
    m_pTree->setColumnWidth(0, int(300*g_xScale));
    m_pTree->header()->setSectionResizeMode(1,QHeaderView::Fixed);
    m_pTree->setColumnWidth(1, int(150*g_xScale));
    m_pTree->header()->setSectionResizeMode(2,QHeaderView::Fixed);
    m_pTree->setColumnWidth(2, int(700*g_xScale));
    m_pTree->header()->setSectionResizeMode(3,QHeaderView::Fixed);
    m_pTree->setColumnWidth(3, int(150*g_xScale));
    m_pTree->header()->setDefaultAlignment(Qt::AlignCenter); // 设置文字居中显示
    m_pTree->header()->setFixedHeight(int(50*g_xScale));           // 固定表头高度
    m_pTree->header()->setSectionsClickable(false);   // 禁用表头点击
    m_pTree->header()->setSectionsMovable(false); // 设置表头不允许拖动
    m_pTree->header()->setStyleSheet(headerStyle);
    m_pTree->setStyleSheet(treeStyle);
    // 禁用水平滚动
    m_pTree->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_pTree->setHorizontalScrollMode(QAbstractItemView::ScrollPerItem);
    // 设置垂直滚动
    m_pTree->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    m_pTree->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    // 配置触摸滚动
    QScroller::grabGesture(m_pTree, QScroller::TouchGesture);
    QScroller::grabGesture(m_pTree, QScroller::LeftMouseButtonGesture);
    QScroller *scroller = QScroller::scroller(m_pTree);
    QScrollerProperties properties = scroller->scrollerProperties();
    // 禁用水平和垂直方向的过度滚动
    properties.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);
    properties.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QScrollerProperties::OvershootAlwaysOff);
    // 设置水平方向的拖动距离为0，实际上禁用了水平滚动
    properties.setScrollMetric(QScrollerProperties::DragStartDistance, 0.0);
    scroller->setScrollerProperties(properties);
    // 设置表格样式，禁用选中效果
    m_pTree->setSelectionMode(QAbstractItemView::NoSelection);
    m_pTree->setFocusPolicy(Qt::NoFocus);

    addSubItem();

    m_pTree->expandAll();
    m_pTree->setItemsExpandable(false);
    mainLayout->addWidget(toolbar);
    mainLayout->addWidget(m_pTree);
    connect(m_pNewButton,&QPushButton::clicked,this,[this](){
        Command cmd;
        addNewRow(cmd);
    });
}

void UpperSettingWidget::saveData()
{
    QList<Command> cmdList;
    int nID = 1;
    for (int i = 0; i < m_pTree->topLevelItemCount(); ++i) {
        QList<Command> subCmdList = getItemData(m_pTree->topLevelItem(i),0,nID);
        cmdList.append(subCmdList);
        nID+= subCmdList.count();
    }
    SysSettingModel::getInstance()->setUpperLimbCmdList(cmdList);
}

void UpperSettingWidget::addSubItem(QTreeWidgetItem *pParentItem, int nParentID)
{
    QList<Command> upperCmd = SysSettingModel::getInstance()->upperLimbCmdList(nParentID);
    for(int i = 0; i < upperCmd.size(); ++i)
    {
        QTreeWidgetItem* item=addNewRow(upperCmd[i],pParentItem);
        addSubItem(item,upperCmd[i].nID);
    }
}

QTreeWidgetItem *UpperSettingWidget::addNewRow(Command cmd, QTreeWidgetItem *pParentItem)
{
    QString editStyle = QString(
                            "QLineEdit {"
                            "    background-color: transparent;"
                            "    border: 0px;"
                            "    padding: 5px;"
                            "    color: lightgray;"
                            "    font: %1px '微软雅黑';"
                            "}"
                            "QLineEdit:disabled {"
                            "    color: gray;"
                            "}"
                            "QLineEdit:focus {"
                            "    border: 1px solid #00A4FF;"
                            "}").arg(int(18*g_xScale));
        QString btnStyle=QString("QPushButton{\
                            background:transparent; \
                            color:#007BFF;\
                            font:%1px \"微软雅黑\"; \
                            border-color: #098CFF;\
                            border-width:1px;}\
                            QPushButton:pressed{ \
                            color:#0056b3; \
                            } \
                            QPushButton:disabled { \
                            color: gray; \
                            }").arg(int(18*g_xScale));
    QTreeWidgetItem * item = NULL;
    if(pParentItem)
        item = new QTreeWidgetItem(pParentItem);
    else
        item = new QTreeWidgetItem(m_pTree);
    QLineEdit* textEdit = new QLineEdit();
    textEdit->setText(cmd.strShowText);
    textEdit->setStyleSheet(editStyle);
    textEdit->setValidator(new QRegExpValidator(QRegExp("[\u4e00-\u9fa5a-zA-Z0-9]+"), this));
    m_pTree->setItemWidget(item,0,textEdit);
    // 将验证器设置到QLineEdit上
    QLineEdit* hexEdit = new QLineEdit();
    QIntValidator *validator = new QIntValidator(0, 255, hexEdit);
    hexEdit->setValidator(validator);
    if(cmd.nHexCmd == 0)
        hexEdit->setText("");
    else
        hexEdit->setText(QString("%1").arg(cmd.nHexCmd));
    hexEdit->setStyleSheet(editStyle);
    m_pTree->setItemWidget(item,1,hexEdit);
    QLineEdit* fileEdit = new QLineEdit();
    fileEdit->setText(cmd.strFile);
    fileEdit->setStyleSheet(editStyle);
    m_pTree->setItemWidget(item,2,fileEdit);

    HotKeyEdit* keyEdit = new HotKeyEdit();
    keyEdit->setKey(cmd.nFuncKey,cmd.nHotKey);
    keyEdit->setStyleSheet(textEdit->styleSheet());
    m_pTree->setItemWidget(item,3,keyEdit);

    // 创建操作按钮容器
    QWidget* buttonWidget = new QWidget(this);
    buttonWidget->setStyleSheet("background-color:#232426;");
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);
    buttonLayout->setContentsMargins(0,0,0,0);
    // 创建按钮
    TouchButton* newBtn = new TouchButton("新建",buttonWidget);
    newBtn->setFixedSize(int(60*g_xScale), int(50*g_xScale));
    newBtn->setStyleSheet(btnStyle);
    connect(newBtn, &QPushButton::clicked, this, [=]() {
        Command cmd;
        addNewRow(cmd,item);
        m_pTree->expandItem(item);
    });
    TouchButton* deleteBtn = new TouchButton("删除",buttonWidget);
    deleteBtn->setFixedSize(int(60*g_xScale), int(50*g_xScale));
    connect(deleteBtn, &QPushButton::clicked, this, [=]() {
        QString strName = textEdit->text().trimmed();
        if(strName.length() == 0 || question(MainWindow::getInstance(), tr("确定要删除动作\"%1\"及其子动作列表？").arg(strName)) == 0)
        {
            delete item;
            m_pNewButton->setFocus();
        }
    });
    deleteBtn->setStyleSheet(btnStyle);

    if(cmd.strShowText.trimmed() == "damp")
    {
        textEdit->setEnabled(false);
        deleteBtn->setEnabled(false);
    }
    // 添加按钮到布局
    buttonLayout->addStretch();
    buttonLayout->addWidget(newBtn);
    buttonLayout->addWidget(deleteBtn);
    buttonLayout->addStretch();
    m_pTree->setItemWidget(item,4,buttonWidget);
    return item;
}

QList<Command> UpperSettingWidget::getItemData( QTreeWidgetItem *item, int nParentID, int nID)
{
    QList<Command> lsCmd;
    QLineEdit *textEdit = qobject_cast<QLineEdit*>(m_pTree->itemWidget(item, 0));
    QLineEdit *hexCmdEdit = qobject_cast<QLineEdit*>(m_pTree->itemWidget(item, 1));
    QLineEdit *fileEdit = qobject_cast<QLineEdit*>(m_pTree->itemWidget(item, 2));
    HotKeyEdit *keyEdit = qobject_cast<HotKeyEdit*>(m_pTree->itemWidget(item, 3));
    if (textEdit && hexCmdEdit && fileEdit && keyEdit) {
        Command cmd;
        cmd.nID = nID;
        cmd.strShowText = textEdit->text();
        cmd.nHexCmd = hexCmdEdit->text().toInt();
        cmd.strFile = fileEdit->text();
        cmd.nHotKey = keyEdit->getHotKey();
        cmd.nFuncKey = keyEdit->getFuncKey();
        cmd.nParentID = nParentID;
        lsCmd.push_back(cmd);
        nID++;
        for(int i = 0; i < item->childCount(); ++i)
        {
            QList<Command> cmdList = getItemData(item->child(i),cmd.nID,nID);
            lsCmd.append(cmdList);
            nID+= cmdList.count();
        }
    }
    return lsCmd;
}

void UpperSettingWidget::hideEvent(QHideEvent *event)
{
    Q_UNUSED(event);
    saveData();
}

